﻿using EmployeeCard.Extensions.Authorizations.Helpers;
using EmployeeCard.IServices;
using EmployeeCard.Model.ViewModels;
using EmployeeCard.Services;

using System.Linq;

using Microsoft.AspNetCore.Mvc;
using Dm;

namespace EmployeeCard.Api.Controllers
{
    /// <summary>
    /// 登录控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class LoginController : ControllerBase
    {
        private readonly IUserServices _userServices;
        public LoginController(IUserServices userServices)
        {
            _userServices = userServices;
        }

        [HttpGet]
        [Route("jsonp")]
        public void Getjsonp(string callBack, long id = 1, string sub = "Admin", int expiresSliding = 30, int expiresAbsoulute = 30)
        {
            TokenInfoViewModel tokenModel = new TokenInfoViewModel();
            tokenModel.Uid = id;
            tokenModel.Sub = sub;

            DateTime d1 = DateTime.Now;
            DateTime d2 = d1.AddMinutes(expiresSliding);
            DateTime d3 = d1.AddDays(expiresAbsoulute);
            TimeSpan sliding = d2 - d1;
            TimeSpan absoulute = d3 - d1;

            string jwtStr = JwtHelper.IssueJwt(tokenModel);
            //重要，一定要这么写
            string response = string.Format("\"value\":\"{0}\"", jwtStr);
            string call = callBack + "({" + response + "})";
            Response.WriteAsync(call);
        }

        [HttpGet]
        [Route("Token")]
        public async Task<IActionResult> GetJWTStr(string name, string pass)
        {
            string jwtStr = string.Empty;
            bool success = false;

            if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(pass))
            {
                return Ok(new { fail = true, message = "账户或密码错误" });
            }

            var userInfo = (await _userServices.Query(x => x.UserName == name && x.Pass == pass)).FirstOrDefault();
            if (userInfo == null)
            {
                return Ok(new { fail = true, message = "账户或密码错误" });
            }

            TokenInfoViewModel tokenModelJwt = new TokenInfoViewModel() { Uid = userInfo.UserId, Sub = "Admin" };
            jwtStr = JwtHelper.IssueJwt(tokenModelJwt);
            success = true;

            return Ok(new { success = success, token = jwtStr });
        }
    }
}
